package com.gk.chat.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Component
public class JwtUtil {
//    private static final String KEY="chat";
    private  String secretKey;
    private  long expirationHours;

    @Value("${jwt.secret-key}")
    public void setSecretKey(String key) {this.secretKey=key;}
    @Value("${jwt.expiration-hours}")
    public void setExpirationHours(long hours){this.expirationHours=hours;}
    //接收业务数据，生成token并返回
    public  String genToken(Map<String,Object> claims){
        return JWT.create()
                .withClaim("mobile",(String) claims.get("mobile"))
                .withExpiresAt(new Date(System.currentTimeMillis()+expirationHours*3600*1000))
                .sign(Algorithm.HMAC256(secretKey));
    }

    //接收token，验证token，并返回业务数据
    public Map<String,Object> parseToken(String token){
        DecodedJWT jwt=JWT.require(Algorithm.HMAC256(secretKey)).build().verify(token);
        Map<String,Object> claims=new HashMap<>();
        claims.put("mobile",jwt.getClaim("mobile").asString());
        return claims;
//        return JWT.require(Algorithm.HMAC256(secretKey))
//                .build()
//                .verify(token)
//                .getClaim("claims")
//                .asMap();
    }
}
